import { SeatsGroupListRespons, SeatsGroupsInfo, SeatsStatusInfo } from 'admin/schema/SeatMonitor';
import { getSeatGroupMonitorList, getSeatMonitorData } from 'admin/servers/servers';
import { Avatar, Card, Empty, List, Tag } from 'antd';
import { DebounceSelect } from 'components/UILibrary/DobounceSelect';

import * as React from 'react';
import CallTime from 'seats/components/CallTime';
import './style.scss';

interface IProps {}

interface ValueType {
  label: string;
  value: number;
}
interface IState {
  /**用户选择的坐席组，用于搜索坐席监控状态入参 */
  selectGroupIds?: number[];
  /**下拉搜索数据源-坐席组列表 */
  optionList?: ValueType[];
  /**坐席详情数据 */
  seatGroupsDetail: SeatsGroupsInfo[];
  /**汇总数据 */
  totalData?: {
    talkTotal: number;
    idleTotal: number;
    busyTotal: number;
    offlineTotal: number;
  };
}

/**坐席监控 */
export default class SeatMonitor extends React.Component<IProps, IState> {
  /**心跳计时器 */
  private timer: any;
  constructor(props: IProps) {
    super(props);
    this.timer = undefined;
    this.state = {
      selectGroupIds: undefined,
      optionList: undefined,
      seatGroupsDetail: [],
      totalData: undefined,
    };
  }

  componentDidMount() {
    this.initPage();
    this.timer = setInterval(() => {
      this.initPage();
    }, 1000);
  }

  componentWillUnmount() {
    this.timer && clearInterval(this.timer);
    this.timer = null;
  }

  initPage = () => {
    this.fetchData();
    // this.checkSeatGroupValid();
  };

  /**检查【用户选择的坐席组】是否有效，已不在列表，则需要手动清除掉选项 */
  checkSeatGroupValid = async () => {
    const list = await this.fetchSeatGroupList();
    console.log('坐席组列表', list);
  };

  /**查询坐席组接口请求 */
  fetchSeatGroupList = (searchWord?: string): Promise<ValueType[]> => {
    return new Promise(resolve => {
      getSeatGroupMonitorList({
        seatsGroupName: searchWord,
      })
        .then(({ data }) => {
          // data = [
          //   { seatsGroupId: 1, seatsGroupName: '邹寒坐席组' },
          //   { seatsGroupId: 2, seatsGroupName: '测试2' },
          //   { seatsGroupId: 3, seatsGroupName: '测试3' },
          //   { seatsGroupId: 4, seatsGroupName: '测试4' },
          //   { seatsGroupId: 5, seatsGroupName: '测试5' },
          //   { seatsGroupId: 6, seatsGroupName: '测试6' },
          //   { seatsGroupId: 7, seatsGroupName: '测试7' },
          //   { seatsGroupId: 8, seatsGroupName: '测试8' },
          //   { seatsGroupId: 9, seatsGroupName: '测试9' },
          //   { seatsGroupId: 10, seatsGroupName: '测试10' },
          //   { seatsGroupId: 11, seatsGroupName: '邹寒坐席组' },
          //   { seatsGroupId: 12, seatsGroupName: '测试测试测试测试2' },
          //   { seatsGroupId: 13, seatsGroupName: '测试测试测试测试3' },
          //   { seatsGroupId: 14, seatsGroupName: '测试测试测试测试4' },
          //   { seatsGroupId: 15, seatsGroupName: '测试测试测试测试5' },
          //   { seatsGroupId: 16, seatsGroupName: '测试测试测试测试6' },
          //   { seatsGroupId: 17, seatsGroupName: '测试测试测试测试7' },
          //   { seatsGroupId: 18, seatsGroupName: '测试测试测试测试8' },
          //   { seatsGroupId: 19, seatsGroupName: '测试测试测试测试9' },
          //   { seatsGroupId: 20, seatsGroupName: '测试测试测试测试10' },
          // ];
          if (!data) {
            resolve([]);
          } else {
            resolve(
              data.map((item: SeatsGroupListRespons) => {
                return {
                  label: item.seatsGroupName,
                  value: item.seatsGroupId,
                };
              })
            );
          }
        })
        .catch(error => {
          console.error(`系统异常: ${JSON.stringify(error)}`);
        });
    });
  };

  fetchData = async () => {
    const { selectGroupIds } = this.state;
    try {
      const { data } = await getSeatMonitorData({
        seatsGroupIds: selectGroupIds,
      });
      console.log('data===', data);
      if (!data) {
        this.setState({
          seatGroupsDetail: [],
          totalData: undefined,
        });
        return;
      }
      const { seatsGroups, ...totalData } = data;
      this.setState({
        seatGroupsDetail: seatsGroups,
        totalData,
      });
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
  };

  // 根据坐席性别转换为图像显示
  getSeatPic = (item: SeatsStatusInfo) => {
    switch (item.sex) {
      case 0:
        return <Avatar src="/webapp/img_man.png" />;
      case 1:
        return <Avatar src="/webapp/img_woman.png" />;
      default:
        return <Avatar src="/webapp/img_man.png" />;
    }
  };

  // 根据坐席状态转换为对应状态tag显示
  getSeatState = (item: SeatsStatusInfo) => {
    // 返回tag结构
    switch (item.status) {
      case 1:
        return <Tag color="success">通话中{<CallTime beginTime={item.talkTime} />}</Tag>;
      case 2:
        return <Tag color="cyan">示闲中</Tag>;
      case 3:
        return <Tag color="error">示忙中</Tag>;
      case 4:
        return <Tag color="default">离线</Tag>;
      default:
        return <Tag color="default">离线</Tag>;
    }
  };

  // Note：任务暂停后，坐席仍显示在搜索框，底部列表入参仍有该坐席组id，在刷新页面或者清除搜索条件恢复即可，暂不考虑复杂逻辑
  // 方案1：后端监控数据接口返回的坐席组数据的时候，过滤掉非进行中的任务，前端根据这个数据，改变【搜索条件数组】。
  // 方案2：前端不停刷新坐席组列表，实时监测【搜索条件数组】，不在实时列表的数据，清除不在【坐席组列表】的坐席组id。

  public render() {
    const { selectGroupIds, seatGroupsDetail, totalData } = this.state;
    return (
      <div className="seat-monitor-page">
        <header className="top">
          <DebounceSelect
            mode="multiple"
            value={selectGroupIds}
            placeholder="请选择坐席组"
            fetchOptions={this.fetchSeatGroupList}
            onChange={newValue => {
              this.setState(
                {
                  selectGroupIds: newValue,
                },
                () => {
                  this.fetchData();
                }
              );
            }}
            showArrow
            allowClear
            style={{ width: '400px' }}
          />
          {totalData && (
            <ul className="seat-states">
              <li className="state state1">
                <span>通话中</span>
                <span>{totalData.talkTotal}</span>
              </li>
              <li className="state state2">
                <span>示闲中</span>
                <span>{totalData.idleTotal}</span>
              </li>
              <li className="state state3">
                <span>示忙中</span>
                <span>{totalData.busyTotal}</span>
              </li>
              <li className="state state4">
                <span>离线</span>
                <span>{totalData.offlineTotal}</span>
              </li>
            </ul>
          )}
        </header>
        <div className="group-list-wrap">
          {seatGroupsDetail.length > 0 &&
            seatGroupsDetail.map((obj: SeatsGroupsInfo, index: number) => {
              return (
                <div className="group-list" key={index}>
                  <div className="group-title">{obj.seatsGroupName}</div>
                  {obj.seatsStatus && obj.seatsStatus?.length > 0 ? (
                    <List
                      className="seat-list"
                      grid={{ gutter: 16, column: 5 }}
                      dataSource={obj.seatsStatus}
                      renderItem={(item: SeatsStatusInfo) => (
                        <List.Item key={item.userId}>
                          <Card>
                            <List.Item.Meta
                              avatar={this.getSeatPic(item)}
                              title={item.nickName}
                              description={this.getSeatState(item)}
                            />
                          </Card>
                        </List.Item>
                      )}
                    />
                  ) : (
                    <Empty
                      image={Empty.PRESENTED_IMAGE_SIMPLE}
                      description={<span>坐席组暂无坐席</span>}
                    />
                  )}
                </div>
              );
            })}
          {!seatGroupsDetail.length && (
            <div className="box-empty">
              <Empty
                image={Empty.PRESENTED_IMAGE_SIMPLE}
                description={
                  <span>
                    未检测到进行中的人机协同任务或人工自动外呼任务，<br></br>
                    因而没有需要监控的坐席组
                  </span>
                }
              />
            </div>
          )}
        </div>
      </div>
    );
  }
}
